#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
#include <string>
#include <arpa/inet.h>
int main() {
    int sockfd;
    struct sockaddr_in servaddr;
    char buffer[1024];

    // 创建UDP套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 初始化服务端地址结构
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET; // IPv4
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务端IP地址
    servaddr.sin_port = htons(8080); // 服务端端口

    // 发送请求到服务端
    std::string request = "Hello from client";
    if (sendto(sockfd, request.c_str(), request.length(), 0,
               (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("sendto failed");
        exit(EXIT_FAILURE);
    }

    std::cout << "Sent request to server: " << request << std::endl;

    // 接收服务端回复
    socklen_t servaddrlen = sizeof(servaddr);
    ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer), 0,
                         (struct sockaddr *)&servaddr, &servaddrlen);
    if (n < 0) {
        perror("recvfrom failed");
        exit(EXIT_FAILURE);
    }

    buffer[n] = '\0'; // 确保字符串以null结尾
    std::cout << "Received response from server: " << buffer << std::endl;

    close(sockfd);
    return 0;
}